package com.lifeonwalden.game.mindustry.entity;

import com.lifeonwalden.game.mindustry.Global;
import com.lifeonwalden.game.mindustry.constant.BulletType;
import com.lifeonwalden.game.mindustry.constant.League;
import com.lifeonwalden.game.mindustry.constant.SurfaceType;
import com.lifeonwalden.game.mindustry.feature.Cannon;
import com.lifeonwalden.game.mindustry.model.TurretProperty;
import com.lifeonwalden.game.mindustry.processor.Scanner;
import com.lifeonwalden.game.mindustry.world.Coordinate;

import java.util.Optional;

public class Turret extends StaticEntity implements Cannon {
    public long allowedShootTime;
    public BulletType bulletType = BulletType.Stone;
    public Scanner scanner;

    public Turret() {
        this.type = SurfaceType.Turret;
        this.hp = SurfaceType.Turret.maxHp;
        this.league = League.Pathfinder;
        scanner = new Scanner(League.Robber, ((TurretProperty) this.type.property).range);
        this.count = 10000;
    }

    @Override
    public void doJobBefore() {
        if (this.destroyed) {
            return;
        } else {
            Optional<Surface> target = this.scan();
            if (target.isPresent()) {
                Surface enemy = target.get();
                Optional<Bullet> bullet = this.shoot((short) (enemy.x + enemy.texture().getRegionWidth() / 2), (short) (enemy.y + enemy.texture().getRegionHeight() / 2));
                if (bullet.isPresent()) {
                    Global.world.addBullet(bullet.get());
                }
            }
        }
    }

    @Override
    public Optional<Bullet> shoot(short targetX, short targetY) {
        if (count > 0) {
            long now = System.currentTimeMillis();
            if (now > allowedShootTime) {
                allowedShootTime = now + ((TurretProperty) this.type.property).shootSpeed;
                count--;
                return Optional.of(new Bullet(this.league, this.bulletType, this.x + this.type.texture.getRegionWidth() / 2, this.y + this.type.texture.getRegionHeight() / 2, targetX, targetY));
            }
        }
        return Optional.empty();
    }

    @Override
    public Optional<Surface> scan() {
        return this.scanner.scan(new Coordinate((short) (this.x + this.type.texture.getRegionWidth() / 2), (short) (this.y + this.type.texture.getRegionHeight() / 2)));
    }
}
